package controllers;

import java.util.Calendar;
import java.util.List;

import models.Information;
import models.Managers;
import models.News;
import models.Programa;
import play.mvc.Controller;
import play.mvc.With;
import service.InformationService;
import service.NewsService;
import service.ProgramaService;

@With(Secure.class)
public class NewsAction extends Controller{

	/**
	 * 查询所有新闻的方法
	 */
	@Check("InformationManage")
	public static void list(){
		List<News> news = NewsService.findAll();
		render(news);
	}
	
	/**
	 * 跳转向添加页面
	 */
	@Check("InformationManage")
	public static void blank(){
		List<Programa> programas = ProgramaService.findTop();
		render(programas);
	}
    
	/**
	 * 新闻的添加方法
	 * 
	 * @param news   新闻对象
	 * @param proId  栏目id
	 */
	@Check("InformationManage")
	public static void create(News news,Long[] proId){
		Long id=0l;
		for (Long long1 : proId) {
			if(long1!=0l){
				id = long1;
			}
		}
		news.managers = Managers.findById(1l);
		news.programa = ProgramaService.findById(id);
		news.newTime = Calendar.getInstance().getTime();
		try {
			NewsService.add(news);
			flash.success("添加成功");
			list();
		} catch (Exception e) {
			System.out.println("类NewAction中的create（）方法抛异常");
			e.printStackTrace();
			flash.success("添加失败");
			blank();
		}
	}
	
	/**
	 * 跳转向修改页面
	 * 
	 * @param id
	 */
	@Check("InformationManage")
	public static void show(Long id){
		News news = NewsService.findById(id);
		List<Programa> programas = ProgramaService.findTop();
		render(news,programas);
	}
	
	/**
	 * 新闻的修改方法
	 * 
	 * @param news  新闻对象
	 * @param id    栏目id
	 */
	@Check("InformationManage")
	public static void save(News news,Long[] proId){
		Long id=0l;
		for (Long long1 : proId) {
			if(long1!=0l){
				id = long1;
			}
		}
		news.managers = Managers.findById(1l);
		news.programa = ProgramaService.findById(id);
		news.newTime = Calendar.getInstance().getTime();
		try {
			NewsService.update(news);
			flash.success("修改成功");
			list();
		} catch (Exception e) {
			System.out.println("#############################NewsAction.save() Exception#####################");
			e.printStackTrace();
			flash.success("修改失败");
			show(news.id);
		}
	}
	
	/**
	 * 删除新闻的方法
	 * 
	 * @param id  新闻id
	 */
	@Check("InformationManage")
	public static void delete(Long id){
		try {
			NewsService.delete(id);
			flash.success("删除成功");
			list();
		} catch (Exception e) {
			System.out.println("###**##########################NewsAction.delete() Exception#####################");
			flash.success("删除失败");
			list();
		}
	}
}
